package com.autoplaza;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Timer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
//import com.djpsoft.moreDroid.ExpandoLayout;

public class DetalleaUTO extends Activity {
	public App_ImageLoader imageLoader;
	ImageView imfoto;
	Timer tim;
	InputStream is = null, is2 = null;
	TextView txtmodelo, txtprecio, txtversion, txtkilometraje, txtlugar, txtcolor1, txtcolor2,txttransmision,encabezado,vestiduras,nf1,nf2,descripcion,fecha,anuncio,titulorelacionadas,descrelacionadas;
	String modelo,numanuncio,anio,marca,transmision,precio,kilometraje,color1,color2,lugar,foto,numfoto,version;
	String result, result2, urlcorta;
	String[] array,array2,array3, array4;
	boolean metodo;
	int noNoticia=0;
	ImageView datoscontacto, telefono,email,compartir,grafica,denunciar, /*guiaprecios,*/ noticias/*, migarage*/;
	String[] ntel;
	WebView myWebView;
	String arrayequipamiento[];
	LinearLayout ll;
	Dialog dialog;
	String[] telefonosarray;
	String[] marcaTel;
	Button[] btarray;
	int j;
	Button bt, btdes, btequipo,btnmenu;
	String content,issearch;
	/*TextView txtGarage;*/
	private ProgressDialog progressDialog;
	String url_string;
	Bundle bundle;
	public int face=-1;
	String url= null;
	String liga=null;
	NumberFormat nf;
	Intent irCompartir;
	LinearLayout hs;
	public Drawable[] drawablearray;
	public Bitmap[] bitmaparray;

	public CargarFotos cargarFotos;

	
	public class CargarFotos extends AsyncTask<Void, Bitmap, Void>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			hs = (LinearLayout) findViewById(R.id.hori);
			hs.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
//					Intent gallery=new Intent(DetalleaUTO.this, Galeria.class);
//					gallery.putExtra("idanuncio", ""+numanuncio);
//					gallery.putExtra("marca", ""+array[4]);
//					gallery.putExtra("modelo", ""+array[0]);
//					gallery.putExtra("year", ""+array[3]);
//					startActivity(gallery);
					
					Intent gallery=new Intent(DetalleaUTO.this, FragmentGallery.class);
					gallery.putExtra("idanuncio", ""+numanuncio);
					gallery.putExtra("marca", ""+array[4]);
					gallery.putExtra("modelo", ""+array[0]);
					gallery.putExtra("year", ""+array[3]);
					gallery.putExtra("fotos", array4);
					startActivity(gallery);
					
					

				}
			});
			
		}
		
		
		@Override
		protected Void doInBackground(Void... params) {
			numanuncio = bundle.getString("numanuncio");
//			metodoinformacion2(numanuncio);
			String url="http://iphone.autoplaza.com.mx/fotos/BuscFotos.aspx?id="+numanuncio;
	        Log.i("url mia", ""+url);
			
			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			}  catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
	       
			
			if (httpEntity != null) {
		
				try {
					is2 = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is2,"utf-8"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is2.close();
		            result2=sb.toString().trim();

		            array4=result2.split("@@@");
			           Log.i("TAM ARRAY", ""+array4.length);

//			        drawablearray = new Drawable[array4.length];
//			        bitmaparray = new Bitmap[array4.length];
		            for(int i=0; i<array4.length; i++){
		            	Log.i("MI ARRAY4["+i+"]", ""+array4[i]);

		            	if(cargarFotos.isCancelled()){
			            	Log.i("BREAK", "BREAK");
		            		break;
		            		
		            	}else{
//		            		Drawable drawable = loadImageFromURL(""+array4[i], "name"+i);
		            		Bitmap bitmap = getBitmapFromURL(""+array4[i]);

			            	publishProgress(bitmap);
		            		
		            	}
//		            	drawablearray[i] = loadImageFromURL(""+array4[i], "name"+i);
		            	
		            }



				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
				}
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Bitmap... values) {
			super.onProgressUpdate(values);
			int[] dimen = Utils.getScreenSize(DetalleaUTO.this);


//	    	for(int i=0; i< array4.length; i++){
	    		
//	    		ImageView iv = new ImageView(this);
//	    		iv.setImageResource(R.drawable.ic_launcher);
//	        	hs.addView(iv);


	    		if(dimen[0] <= 320){
	            	Log.i("DENSITY", "MEDIUM");
	            	
	        		ImageView iv = new ImageView(DetalleaUTO.this);
	        		iv.setLayoutParams(new LayoutParams(120,90));
	        		iv.setPadding(5, 0, 5, 0);
//	        		String url=array4[i].replace(" ", "%20");
//	        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

//	    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
	    			iv.setImageBitmap(values[0]);

//	            	iv.setImageResource(R.drawable.ic_launcher);
	            	hs.addView(iv);
//	            	mPager.addView(iv);
	        	}else if( (dimen[0] > 320) && (dimen[0] <=480 )){
	            	Log.i("DENSITY", "HIGH");
	        		ImageView iv = new ImageView(DetalleaUTO.this);
	        		iv.setLayoutParams(new LayoutParams(180,135));
	        		iv.setPadding(5, 0, 5, 0);
//	        		String url=array4[i].replace(" ", "%20");
//	        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

//	    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
	    			iv.setImageBitmap(values[0]);

//	            	iv.setImageResource(R.drawable.ic_launcher);
	            	hs.addView(iv);
//	            	mPager.addView(iv);
	        	}else if(dimen[0] > 480){
	            	Log.i("DENSITY", "EXTRA HIGH");
	        		ImageView iv = new ImageView(DetalleaUTO.this);
	        		iv.setLayoutParams(new LayoutParams(240,180));
	        		iv.setPadding(5, 0, 5, 0);
//	        		String url=array4[i].replace(" ", "%20");
//	        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

//	    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
	    			iv.setImageBitmap(values[0]);

//	            	iv.setImageResource(R.drawable.ic_launcher);
	            	hs.addView(iv);
//	            	mPager.addView(iv);
	        	}

//	    		String url=array4[i].replace(" ", "%20");
////	    		iv.setOnClickListener(getOnClickDoSomething(""+url, i));
	//
//				Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
//				iv.setImageDrawable(imagen);
	//
////	        	iv.setImageResource(R.drawable.ic_launcher);
//	        	hs.addView(iv);
//	        	mPager.addView(iv);
//	    	}

			
			
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			crearImagenes();
			
		}
		
		
	}
	

	public class CargarContenido extends AsyncTask<String, String, String>{


		@Override
		protected void onPreExecute() {
			super.onPreExecute();

//			progressDialog = ProgressDialog.show(DetalleaUTO.this, "",
//					"Cargando...", true, true, new OnCancelListener() {
//
//				@Override
//				public void onCancel(DialogInterface arg0) {
//					finish();
//				}
//			});
		}


		@Override
		protected String doInBackground(String... params) {

			if ( bundle != null ) {
				content=bundle.getString("content");
				//SPLASH
				SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
				issearch=preferences.getString("iscontent", "null");
				if(issearch.equals("true")){
					Log.i("PUBLICIDAD", "CONTENT");
					url_string = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca=&modelo=&busqueda="+content;
					//	        	      myWebView.loadUrl("http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca=&modelo=&busqueda="+content);
				}else{
					SharedPreferences preferences2= getSharedPreferences("Carro",Context.MODE_PRIVATE);
					String marcasplash=preferences2.getString("marca", "[Cualquiera]");
					String modeloplash=preferences2.getString("modelo", "[Cualquiera]");
					boolean marcabool=marcasplash.equals("[Cualquiera]");
					boolean modelobool=modeloplash.equals("[Cualquiera]");
					if(marcabool == false && modelobool == true){
						url_string = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+marcasplash+"&modelo=&busqueda=";
						//		        	      myWebView.loadUrl("http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+marcasplash+"&modelo=&busqueda=");
						Log.i("PUBLICIDAD", "2");

					}
					if(modelobool == false && marcabool == false){
						url_string = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+modeloplash+"&modelo=&busqueda=";
						//		        	      myWebView.loadUrl("http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+modeloplash+"&modelo=&busqueda=");
						Log.i("PUBLICIDAD", "3");

					}

				}
				numanuncio = bundle.getString("numanuncio");
				Log.i("NUM_ANUNCIO", numanuncio);
				metodoinformacion(numanuncio);
//				metodoinformacion2(numanuncio);
				
				
				precio = bundle.getString("precio");
				foto = bundle.getString("foto"); 
				numfoto = bundle.getString("numfoto");
				version = bundle.getString("version");

			}

			return null;

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();

			myWebView.setBackgroundColor(Color.parseColor("#00000000"));
			myWebView.loadUrl(url_string);


			NumberFormat nf = NumberFormat.getInstance();
			nf = NumberFormat.getInstance(Locale.ENGLISH);
			txtmodelo.setText(""+array[4]+" "+array[0]+" "+array[3]);
			encabezado.setText(""+array[4]+" "+array[0]+" "+array[3]);
			txtprecio.setText("$ "+nf.format(Double.parseDouble(array[8])) +" M.N");
			txtversion.setText(""+version);
			txtkilometraje.setText(""+array[10] +" km");
			txtlugar.setText(""+array[13]);
			txtcolor1.setText(""+array[11]+"  / "+array[16]);
			vestiduras.setText(""+array[14]);
			txttransmision.setText(""+array[7]);
			nf1.setText(""+numfoto);

			//			if(checkData() == true){
			//				txtGarage.setText("Eliminar de mi Garage");
			//			}else{
			//				txtGarage.setText("Agregar a mi Garage");
			//
			//			}


			if(noNoticia==0){
				//				LinearLayout tit=(LinearLayout) findViewById(R.id.notrelacionadas);
				//				LinearLayout notdet=(LinearLayout) findViewById(R.id.detnoticia);
				//				tit.setVisibility(View.GONE);
				//				notdet.setVisibility(View.GONE);



			}else{
				//				nf2.setText(""+array3[5]);
				//				titulorelacionadas.setText(""+array3[2]);
				//				descrelacionadas.setText(""+array3[3]);
				//				Drawable image2 = ImageOperations(getApplicationContext(),"","image.jpg", ""+array3[4]);
				//				ImageView imgView2 = new ImageView(getApplicationContext());
				//				imgView2 = (ImageView)findViewById(R.id.foto2);
				//				imgView2.setImageDrawable(image2);

			}
			//			opciones.setText(""+array[28]);
			descripcion.setText(""+array[35]);
			descripcion.setTextSize(14);

		
			
			fecha.setText(""+array2[0]);
			anuncio.setText(""+array[2]);



			Drawable image = ImageOperations(getApplicationContext(),"","image.jpg", ""+foto);
			ImageView imgView = new ImageView(getApplicationContext());
			imgView = (ImageView)findViewById(R.id.foto);
			imgView.setImageDrawable(image);

			imgView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent gallery=new Intent(DetalleaUTO.this, Galeria.class);
					gallery.putExtra("idanuncio", numanuncio);
					gallery.putExtra("marca", ""+array[4]);
					gallery.putExtra("modelo", ""+array[0]);
					gallery.putExtra("year", ""+array[3]);
					startActivity(gallery);

				}
			});



			datoscontacto.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						Intent irDatos=new Intent(DetalleaUTO.this, DatosContacto.class);
						irDatos.putExtra("from", "nolista");
						irDatos.putExtra("nombre", array[22]);
						irDatos.putExtra("email", array[23]);
						irDatos.putExtra("telefonos", array[24]);
						irDatos.putExtra("hora1", array[29]);
						irDatos.putExtra("hora2", array[30]);
						irDatos.putExtra("encabezado", ""+array[4]+" "+array[0]+" "+array[3]);
						irDatos.putExtra("marcadotelefonos", array[56]);
						irDatos.putExtra("idanuncio", ""+array[1]);
						irDatos.putExtra("marca", ""+array[4]);
						irDatos.putExtra("modelo", ""+array[0]);
						irDatos.putExtra("year", ""+array[3]);
						startActivity(irDatos);
					}else{
						dialogoInternet();
					}
				}
			});

			//FACEBOOK
			telefono.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						face = 1;
						new CargarInfo().execute("");

					}else{
						dialogoInternet();
					}



				}
			});

			//TWITTER
			email.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						try {
							face = 2;
							new CargarInfo().execute("");

						} catch (Exception e) {
						}


					}else{
						dialogoInternet();
					}


					//				Intent irEmail=new Intent(DetalleaUTO.this, ContactoEmail.class);
					//				startActivity(irEmail);				
				}
			});
			compartir.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						new CargarInfo2().execute("");

					}else{
						dialogoInternet();
					}

				}
			});
			grafica.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						Intent irGrafica=new Intent(DetalleaUTO.this, Grafica.class);
						irGrafica.putExtra("numanuncio", array[1]);
						startActivity(irGrafica);
					}else{
						dialogoInternet();
					}

				}
			});
			denunciar.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if(isNetwork()==true){
						Intent irDenuncia=new Intent(DetalleaUTO.this, Denunciar.class);
						irDenuncia.putExtra("numanuncio", array[1]);
						startActivity(irDenuncia);
					}else{
						dialogoInternet();
					}

				}
			});

			//		guiaprecios.setOnClickListener(new OnClickListener() {
			//			
			//			@Override
			//			public void onClick(View arg0) {
			//				Intent gprecios = new Intent(DetalleaUTO.this, GuiaPrecios.class);
			//				startActivity(gprecios);
			//			}
			//		});

			//		noticias.setOnClickListener(new OnClickListener() {
			//			
			//			@Override
			//			public void onClick(View arg0) {
			//				// TODO Auto-generated method stub
			//				
			//			}
			//		});

			//		migarage.setOnClickListener(new OnClickListener() {
			//			
			//			@Override
			//			public void onClick(View arg0) {
			//				if(checkData() == true){
			//					//Abrimos la base de datos 'DBUsuarios' en modo escritura
			//			        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
			//			        SQLiteDatabase db = usdbh.getWritableDatabase();
			//					
			//			        //Si hemos abierto correctamente la base de datos
			//			        if(db != null)
			//			        {
			//						//Eliminar un registro
			//						db.execSQL("DELETE FROM Garage WHERE anuncio='"+array[1]+"' ");
			//						
			//			            //Cerramos la base de datos
			//			            db.close();
			//			        }
			//					txtGarage.setText("Agregar a mi Garage");
			//					Toast.makeText(getApplicationContext(), "Auto eliminado de Mi Garage exitosamente", Toast.LENGTH_LONG).show();
			//
			//				}else{
			//					//Abrimos la base de datos 'DBUsuarios' en modo escritura
			//			        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
			//			        SQLiteDatabase db = usdbh.getWritableDatabase();
			//					
			//			        //Si hemos abierto correctamente la base de datos
			//			        if(db != null)
			//			        {
			//			            //Insertamos los datos en la tabla Usuarios
			//			            db.execSQL("INSERT INTO Garage (foto, marca, modelo, version, year, precio," +
			//			            		"kilometraje, estado, transmision, color, colorint, financiamiento," +
			//			            		"vestidura, anuncio, numfoto, comparativo) " +
			//			                           "VALUES ('" + foto +"', '" + array[4] +"', '" + array[0]  +"'" +
			//			                           		", '" + version +"', '" + array[3]  +"', '" + array[8]  +"'" +
			//			                           		", '" + array[10]  +"', '" + array[13]  +"', '" + array[7] +"'" +
			//			                           		", '" + array[11] +"', '" + array[16] +"', '" + array[9] +"'" +
			//			                           				", '" + array[14] +"', '" + array[1] +"', '" + numfoto +"'" +
			//			                           						", 'no')");
			//			            //Cerramos la base de datos
			//			            db.close();
			//			        }
			//			        txtGarage.setText("Eliminar de mi Garage");
			//					Toast.makeText(getApplicationContext(), "Auto agregado a Mi Garage exitosamente", Toast.LENGTH_LONG).show();
			//				}
			//			}
			//		});


			arrayequipamiento=array[28].trim().split(";");
			for(int i=0; i<arrayequipamiento.length; i++){
				if(i < 5){
					Log.i("TAG", ""+arrayequipamiento[i]);
					TextView tv=new TextView(getApplicationContext());
					tv.setTextSize(14);
					tv.setTextColor(Color.BLACK);
					if(!arrayequipamiento[i].endsWith(":")){



						tv.setText("      *"+arrayequipamiento[i]);



					}else{
						tv.setTypeface(null,Typeface.BOLD);

						tv.setText(""+arrayequipamiento[i]);

					}

					ll.addView(tv);
				}
				

			}
			
			if(arrayequipamiento.length > 4){
				btequipo.setVisibility(View.VISIBLE);
				btequipo.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent goDetalleTexto = new Intent(DetalleaUTO.this, DetalleTexto.class);
						goDetalleTexto.putExtra("texto", ""+array[28]);	
						goDetalleTexto.putExtra("equipamiento", "si");
						goDetalleTexto.putExtra("encabezado", ""+array[4]+" "+array[0]+" "+array[3]);


						startActivity(goDetalleTexto);
					}
				});
			}
			

			cargarFotos = new CargarFotos();
			cargarFotos.execute();
//			new CargarFotos().execute();

//			progressDialog.dismiss();

		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		Log.i("texto", ""+descripcion.getLineCount());
		Log.i("texto", ""+descripcion.getLineHeight());
		if(descripcion.getLineCount() > 4){
			btdes.setVisibility(View.VISIBLE);
			btdes.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
						Intent goDetalleTexto = new Intent(DetalleaUTO.this, DetalleTexto.class);
						goDetalleTexto.putExtra("texto", ""+array[35]);
						goDetalleTexto.putExtra("equipamiento", "");
						goDetalleTexto.putExtra("encabezado", ""+array[4]+" "+array[0]+" "+array[3]);

						startActivity(goDetalleTexto);
				}
			});
		}
		
	}
	
	
    private void crearImagenes() {

    	ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar1);
    	progress.setVisibility(View.GONE);
    	
    	
    }


	private void InicializeViews() {
		bundle = this.getIntent().getExtras(); 


		myWebView = (WebView)this.findViewById(R.id.webView1);
		myWebView.getSettings().setJavaScriptEnabled(true);
		myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);	

		imageLoader = new App_ImageLoader(DetalleaUTO.this.getApplicationContext());
		txtmodelo = (TextView) findViewById(R.id.modelo);
		txtprecio=(TextView) findViewById(R.id.lblprecio);
		txtversion=(TextView) findViewById(R.id.version);
		txtkilometraje=(TextView) findViewById(R.id.lblkilom);
		txtlugar=(TextView) findViewById(R.id.lblubicacion);
		txtcolor1=(TextView) findViewById(R.id.lblcolors);
		txttransmision=(TextView) findViewById(R.id.lbltransmision);
		encabezado=(TextView) findViewById(R.id.encabezado);
		vestiduras=(TextView) findViewById(R.id.lblvestiduras);
		nf1=(TextView) findViewById(R.id.nf);
		//			nf2=(TextView) findViewById(R.id.nf2);
		descripcion= (TextView) findViewById(R.id.des);
		fecha= (TextView) findViewById(R.id.fecha);
		anuncio= (TextView) findViewById(R.id.anuncio);
		//			titulorelacionadas= (TextView) findViewById(R.id.titulorelacionadas);
		//			descrelacionadas= (TextView) findViewById(R.id.descrelacionadas);
		ll=(LinearLayout) findViewById(R.id.ll_equipamiento);

		//			txtGarage = (TextView) findViewById(R.id.txtaddgarage);

		datoscontacto=(ImageView) findViewById(R.id.datos);
		telefono=(ImageView) findViewById(R.id.telefono);
		email=(ImageView) findViewById(R.id.email);
		compartir=(ImageView) findViewById(R.id.compartir);
		grafica=(ImageView) findViewById(R.id.grafica);
		denunciar=(ImageView) findViewById(R.id.denunciar);
		btdes = (Button) findViewById(R.id.button1);
		btequipo = (Button) findViewById(R.id.button2);
		//			guiaprecios=(ImageView) findViewById(R.id.idguia);
		//			noticias=(ImageView) findViewById(R.id.idnoticias);
		//			migarage=(ImageView) findViewById(R.id.idgarage);
	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.detalle);
		
		btnmenu = (Button) findViewById(R.id.btn_menu);
		btnmenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent goManuLateral = new Intent(DetalleaUTO.this, MenuLateral.class);
				goManuLateral.putExtra("clase","Detalle");
				startActivity(goManuLateral);

			}
		});

		int size = Utils.getScreenSize2(DetalleaUTO.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout2);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(25, 25);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout2);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(50, 50);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout2);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(70, 70);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		InicializeViews();

		progressDialog = new ProgressDialog(DetalleaUTO.this);
		progressDialog.setMessage("Cargando...");
		progressDialog.show();

		metodo = isNetwork();
		if(metodo==false){
			dialogoInternet();
		}else{
			new CargarContenido().execute("");
//			new CargarFotos().execute();

		}
	}

	protected boolean checkData() {
		boolean bool = false;
		//Abrimos la base de datos 'DBUsuarios' en modo escritura
		SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
		SQLiteDatabase db = usdbh.getWritableDatabase();
		String[] campos = new String[] {"anuncio"};
		String[] args = new String[] {""+array[1]};

		Cursor c = db.query("Garage", campos, "anuncio=?", args, null, null, null);

		//Nos aseguramos de que existe al menos un registro
		if (c.moveToFirst()) {
			bool = true;
		}else{
			bool = false;
		}

		db.close();
		return bool;
	}





	protected String getUrlCorta() {

		metodo = isNetwork();
		if(metodo==false){
			dialogoInternet();
		}else{

			String url="http://autoplaza.mx/?api=apmx&u=http://www.autos-usados.autoplaza.com.mx/Autos/"+
					array[4]+"-"+array[0]+""+array[3]+"~id"+array[2]+".aspx";
			Log.i("url mia", ""+url);

			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			}  catch (IOException e) {
			}

			HttpEntity httpEntity = webServerResponse.getEntity();

			if (httpEntity != null) {

				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					urlcorta=sb.toString().trim();
					Log.i("URL CORTA", urlcorta+"");

				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
				}
			}


		}
		return urlcorta;

	}


	void downloadBitmapImage()
	{
		InputStream input;
		try {
			URL url = new URL (""+foto);
			input = url.openStream();
			byte[] buffer = new byte[1500];
			OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/shareimage.png");
			try 
			{     
				int bytesRead = 0;
				while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) 
				{
					output.write(buffer, 0, bytesRead);
				}
			} 
			finally 
			{
				output.close();
				buffer=null;
			}
		} 
		catch(Exception e) 
		{
			Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
		}
	}


	protected void crearDialog() {

		dialog=new Dialog(DetalleaUTO.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		dialog.setContentView(R.layout.customdialog);
		dialog.show();

		ll=(LinearLayout)dialog.findViewById(R.id.linearllamada);
		Button btcancel=(Button) dialog.findViewById(R.id.btcancelar);
		btcancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				dialog.cancel();
			}
		});
		marcaTel=array[56].split("%%%");
		telefonosarray=array[24].split(",");
		btarray=new Button[telefonosarray.length];
		for(int i=0;i<telefonosarray.length;i++){
			j=i;
			if(telefonosarray[i].trim().startsWith("ID")){

			}else{
				RelativeLayout relative=new RelativeLayout(this);
				relative.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

				LinearLayout lintel=new LinearLayout(this);
				lintel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				lintel.setOrientation(LinearLayout.VERTICAL);
				String[] telarray=telefonosarray[i].split(":");
				TextView tipo=new TextView(this);
				tipo.setText(""+telarray[0]);
				tipo.setTypeface(null,Typeface.BOLD);
				tipo.setTextColor(Color.RED);

				TextView numero=new TextView(this);
				numero.setText(""+telarray[1]);
				numero.setTypeface(null,Typeface.BOLD);
				numero.setTextColor(Color.BLACK);

				lintel.addView(tipo);
				lintel.addView(numero);

				bt=new Button(this);
				bt.setBackgroundResource(R.drawable.selectorllamada);
				bt.setOnClickListener(getOnClickDoSomething(bt, ""+marcaTel[i]));

				relative.addView(lintel);
				relative.addView(bt);

				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)lintel.getLayoutParams();
				params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				lintel.setLayoutParams(params); //causes layout update

				RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams)bt.getLayoutParams();
				params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
				bt.setLayoutParams(params2);

				ll.addView(relative);

			}
		}

	}

	View.OnClickListener getOnClickDoSomething(final Button button, final String texto)  {
		return new View.OnClickListener() {
			public void onClick(View v) {

				Intent callIntent = new Intent();
				callIntent = new Intent(Intent.ACTION_DIAL,
						Uri.parse("tel:"+texto));

				startActivity(callIntent);	
			}
		};
	}


	public void funcionIniciarContextMenuParaBoton2(View v) {
		registerForContextMenu(v);
		openContextMenu(v);
	}



	private void metodoinformacion(String numanuncio2) {
		String url="http://iphone.autoplaza.com.mx/fastSearch/fastSearchIphone.aspx?querybiphone=yes&id="+numanuncio2+"&News=yes";
		Log.i("url mia", ""+url);

		URI myURI = null;
		try {
			myURI = new URI(url);
		} catch (URISyntaxException e) {
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
		}  catch (IOException e) {
		}

		HttpEntity httpEntity = webServerResponse.getEntity();


		if (httpEntity != null) {

			try {
				is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result=sb.toString().trim();
				array2=new String[1];
				array3=new String[6];
				array=result.split("@@@");
				Log.i("TAM ARRAY", ""+array.length);


				array2 = array[18].split("T");


				if(array.length == 60){
					array3 = array[57].split("%%%");
					for(int i=0; i<array3.length; i++){
						Log.i("MI ARRAY3["+i+"]", ""+array3[i]);
					}
					noNoticia=1;

				}



				for(int i=0; i<array.length; i++){
					Log.i("MI ARRAY1["+i+"]", ""+array[i]);
				}
				for(int i=0; i<array2.length; i++){
					Log.i("MI ARRAY2["+i+"]", ""+array2[i]);
				}


			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
			}
			
			
			
			
			
			
			
			
		}

	}
	
	public Drawable loadImageFromURL(String url, String name) {
	    try {
	        InputStream is = (InputStream) new URL(url).getContent();
	        Drawable d = Drawable.createFromStream(is, name);
	        return d;
	    } catch (Exception e) {
	        return null;
	    }
	}
	
	public Bitmap getBitmapFromURL(String src) {
	    try {
	        URL url = new URL(src.replace(" ", "%20"));
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoInput(true);
	        connection.connect();
	        InputStream input = connection.getInputStream();
	        Bitmap myBitmap = BitmapFactory.decodeStream(input);
	        return myBitmap;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
	} // Author: silentnuke
	
	private Drawable ImageOperations(Context ctx, String url, String saveFilename, String myurl) {
		try {
			InputStream is = (InputStream) this.fetch(myurl);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	public boolean isNetwork(){
		NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();

		if(networkInfo == null || !networkInfo.isConnected()) {
			return false;
		}
		return true;
	}

	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(DetalleaUTO.this);
		builder.setMessage("Necesita conexión a Internet")
		.setCancelable(false)
		.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		

	}

	public class CargarInfo extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(DetalleaUTO.this, "",
					"Cargando...", true, true, new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface arg0) {
					finish();
				}
			});			
		}

		@Override
		protected String doInBackground(String... params) {
			//			getUrlCorta();
			try{
				if(face == 1){
//					url = "http://www.facebook.com/sharer/sharer.php?u="+getUrlCorta();
					
					url = "http://www.autos-usados.autoplaza.com.mx/Autos/"+
						array[4]+"-"+array[0]+""+array[3]+"~id"+array[2]+".aspx";

					nf = NumberFormat.getInstance();
					nf = NumberFormat.getInstance(Locale.ENGLISH);
					

				}else{
//					liga=getUrlCorta();
//					liga="http://www.autos-usados.autoplaza.com.mx/Autos/"+
//						array[4]+"-"+array[0]+""+array[3]+"~id"+array[2]+".aspx";
					liga="http://www.autos-usados.autoplaza.com.mx/Autos/Detalle~id"+array[2]+".aspx";

					nf = NumberFormat.getInstance();
					nf = NumberFormat.getInstance(Locale.ENGLISH);

				}	
			}
			catch (Exception e) {
				face = 10;
			}


			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(face == 1){
				Intent intent = new Intent(DetalleaUTO.this, MiFacebook.class);
		    	intent.putExtra(MiFacebook.FACEBOOK,url);
		    	intent.putExtra("dato", ""+array[4]+" "+array[0]+" "+array[3]+" el costo es de: $"+nf.format(Double.parseDouble(array[8])) +" M.N , encuentre su próximo auto en Autoplaza");
		    	startActivity(intent);
				
				
//				Intent i = new Intent(Intent.ACTION_VIEW);
//				i.setData(Uri.parse(url));
//				startActivity(i);
			}else if(face == 10){
				Toast.makeText(getApplicationContext(), "No disponible por el momento", Toast.LENGTH_SHORT).show();
			}else{
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/share?text="+"Encontré este auto que están vendiendo en @AutoplazaMexico, "+""+array[4]+" "+array[0]+" "+array[3]+
						" el costo es de: $"+nf.format(Double.parseDouble(array[8])) +" M.N "+liga));
				startActivity(browserIntent);
			}
			progressDialog.dismiss();
		}


	}

	public class CargarInfo2 extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(DetalleaUTO.this, "",
					"Cargando...", true, true, new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface arg0) {
					finish();
				}
			});
		}


		@Override
		protected String doInBackground(String... params) {
			nf = NumberFormat.getInstance();
			nf = NumberFormat.getInstance(Locale.ENGLISH);
			//			url = getUrlCorta();
			url = "";


			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			irCompartir=new Intent(DetalleaUTO.this, Compartir.class);
			irCompartir.putExtra("idanuncio", ""+array[1]);
			irCompartir.putExtra("foto", ""+foto);

			irCompartir.putExtra("cadena", "Encontré este auto que están vendiendo en @AutoplazaMexico, "+""+array[4]+" "+array[0]+" "+array[3]+
					" el costo es de: $"+nf.format(Double.parseDouble(array[8])) +" M.N "+url);
			startActivity(irCompartir);


			progressDialog.dismiss();
		}
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		cargarFotos.cancel(true);
		
	}



}


